package org.jasig.cas.ticket.registry;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.stereotype.Service;



@Service("ticketRegistryService")
public class TicketRegistryService {
	
	@Autowired
	private JdbcTemplate jdbctemplate;
	
	public void install(final String ticket){
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-mm-dd");
		final String createDate = sdf.format(new Date()); 
		
		final String sql = " insert into pure_ticket (ticket,createdate) values(?,?)";
		jdbctemplate.update(new PreparedStatementCreator() {
			
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setString(1, ticket);
				ps.setString(2,createDate);
				return ps;
			}
		});
	}
	
	public void update(final String ticket){
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-mm-dd");
		final String createDate = sdf.format(new Date()); 
		
		final String sql = " update  pure_ticket set ticket=?,createdate=? ";
		jdbctemplate.update(new PreparedStatementCreator() {
			
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setString(1, ticket);
				ps.setString(2, createDate);
				return ps;
			}
		});
	}
	
	public void delete(TicketBean ticketBean){
		final TicketBean tb = ticketBean;
		final String sql = " delete from pure_ticket where ticket=? "
				+" and to_date(t.createdate,'yyyy-mm-dd') = to_date( ? ,'yyyy-mm-dd') ";
		jdbctemplate.update(new PreparedStatementCreator() {
			
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setString(1, tb.getTicket());
				ps.setString(2, tb.getCreateDate());
				return ps;
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public String getTicket(String ticket){
		String sql = "select t.ticket from pure_ticket t where t.ticket = ? "
				+" and to_date(t.createdate,'yyyy-mm-dd') = to_date( ? ,'yyyy-mm-dd') ";
		
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-mm-dd");
		String createDate = sdf.format(new Date()); 
		List<TicketBean> list = jdbctemplate.query(sql, new Object[]{ticket,createDate},new BeanPropertyRowMapper(TicketBean.class) );
		return list==null||list.size()==0?null:list.get(0).getTicket();
	}
	
}
